package com.stockz.equity.charting.util;

import java.awt.Container;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.aop.target.dynamic.Refreshable;
import org.springframework.beans.BeansException;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import com.stockz.equity.pattern.Child;
import com.stockz.equity.pattern.Parent;

@Component
public class UIConfigurationUtil{

	@SuppressWarnings("unchecked")
	public void configureParentsAndChildren()
			throws BeansException {
		Collection<Child> childCollection = ContextUtil.getApplicationContext().getBeansOfType(Child.class).values();
		List<Child> orderedChildList = new ArrayList<Child>();
		List<Child> unorderedChildList = new ArrayList<Child>();
		for(Parent parent : ContextUtil.getApplicationContext().getBeansOfType(Parent.class).values()){
			for(Child child : childCollection){
				for(Class parentClass : child.getParents()){
					if(parentClass.isAssignableFrom(parent.getClass())){

						if(child instanceof Refreshable){
							((Refreshable)child).refresh();
						}
						
						if(child instanceof java.awt.Component){
							if(child instanceof Ordered){
								orderedChildList.add(child);
							}else{
								unorderedChildList.add(child);
							}
						}
					}
				}
			}
			OrderComparator.sort(orderedChildList);
		 if(parent instanceof Container){
				Container container = (Container)parent;
				for(Child child : unorderedChildList){
					container.add((java.awt.Component)child);
				}
				for(int i = 0; i < orderedChildList.size(); i++){
					container.add((java.awt.Component)orderedChildList.get(i),i);
				}
			}
			unorderedChildList.clear();
			orderedChildList.clear();
			
		}
	}
}
